//
//  BilibiliVideo.swift
//  RoBiliBiliHotVideo
//
//  Created by 罗万能 on 2025/7/5.
//


import Foundation

// MARK: - 视频数据模型
public struct ParsingVideo: Codable ,Sendable{
    let code: Int
    let msg: String
    let title: String
    let imgurl: URL
    let desc: String
    let data: [VideoItem]
    let user: UserInfo
    let text: ApiMeta
    
    // MARK: - 视频条目
    public struct VideoItem: Codable ,Sendable {
        let title: String
        let duration: Int
        let durationFormat: String
        let accept: [String]          // 支持的清晰度
        let videoURL: URL             // 视频地址
        
        // 自定义初始化方法（从API的data元素初始化）
        init?(_ dataItem: VideoItem) {
            self = dataItem
        }
        
        // 处理JSON键名映射
        private enum CodingKeys: String, CodingKey {
            case title
            case duration
            case durationFormat
            case accept
            case videoURL = "video_url"
        }
    }
    
    // MARK: - 用户信息
    public struct UserInfo: Codable  ,Sendable{
        let name: String
        let userImg: URL
        
        private enum CodingKeys: String, CodingKey {
            case name
            case userImg = "user_img"
        }
    }
    
    // MARK: - API元数据
    public struct ApiMeta: Codable  ,Sendable{
        let msg: String
        let copyright: String
    }
    
    // MARK: - 解析整个API响应
    public static func create(from data: Data)  -> ParsingVideo? {
        do{
            let decoder = JSONDecoder()
            let result =  try decoder.decode(ParsingVideo.self, from: data)
            return result
        }catch{
            print(error)
            return nil
        }
    }
}

// MARK: - 便捷扩展
extension ParsingVideo.VideoItem {
    /// 获取主要清晰度（去除重复/冗余信息）
    public var primaryQualities: [String] {
        return accept.map {
            $0.replacingOccurrences(of: "高清 ", with: "")
                .replacingOccurrences(of: "流畅 ", with: "")
        }
    }
    
    /// 获取时长（秒）
    public var durationInSeconds: Int {
        return duration / 1000  // 假设原数据是毫秒
    }
}
